<?php
/**
 * Created by PhpStorm.
 * User: QM
 * Date: 2018/3/29
 * Time: 9:49
 */
namespace App\Command;

use App\Commen\ExportCommen;

/**
 * Class ExportConsumer
 * @package App\Command
 */
class ExportConsumer extends AbstractBase
{
    private $savePath;  //文件保存路径
    private $result;
    private $everyFileNum;
    private $everyTimeNum;

    /**
     * ExportConsumer constructor.
     */
    public function __construct()
    {
        parent::__construct("FKL2");
        $this->savePath = $this->config['export_file_path'];
        //查询数据 100000条数据一个文件
        $this->everyFileNum = $this->config['every_file_num'];
        $this->everyTimeNum = $this->config['every_time_num'];
    }

    /**
     * 消费方法
     * @param \AMQPQueue $que
     * @return mixed|void
     * @throws \Exception
     */
    public function consumerMessage(\AMQPQueue $que)
    {
        if (empty($this->msgQueue)) {
            $this->logger->info(sprintf("que【%s】consumerMessage数据为空", $this->queName));

            return;
        }
        foreach ($this->msgQueue as $key => $row) {
            try {
                if (empty($row['title']) || empty($row['export_type']) || empty($row['export_id']) || empty($row['sql']) || empty($row['file_name']) || empty($row['count'])) {
                    $this->ackData($que, $key, $row);
                    $this->logger->info(sprintf("que【%s】数据不齐全", $this->queName));

                    continue;
                }
                if (!$this->validation($row)) {
                    $this->ackData($que, $key, $row);
                    $this->logger->info(sprintf("que【%s】".$this->result['message'], $this->queName));

                    continue;
                }
                $export = new ExportCommen();
                $export->parsingTitle($row['title']);
                $files = ceil($row['count']/$this->everyFileNum);
                $filesName = array();
                $rate = 1;
                for ($i = 1; $i <= $files; $i++) {
                    $filesName[] = $export->createFile($row['file_name'].$i, $row['export_type'], $this->savePath);
                    $page = ceil($this->everyFileNum/$this->everyTimeNum);
                    for ($j = 1; $j <= $page; $j++) {
                        $skip = ($j - 1)*$this->everyTimeNum + ($i - 1)*$this->everyFileNum;
                        $insertData = $this->dbconn->fetchAll($row['sql']." limit $skip,$this->everyTimeNum");
                        $export->insertFile($insertData);
                        $this->updateType($row['export_id'], 1, round($rate/($files*$page), 2)*100);
                        $rate++;
                    }
                    $export->closeFile();
                }
                //多个文件生成压缩包
                $href = $export->createZip($filesName, $row['file_name']);
                $this->updateType($row['export_id'], 1, 100, basename($href), $export->getFileSize($href));
                $this->ackData($que, $key, $row);

            } catch (\Exception $e) {
                $this->ackData($que, $key, $row, true);
                $this->logger->error(sprintf("que【%s】 报错信息【%s】", $this->queName, $e->getMessage()));

            }
        }
        $this->msgQueue = array();

        return;
    }

    /**
     * 任务验证
     */
    private function validation($row)
    {
        if (empty($row['export_id'])) {
            $this->_error(401, "任务ID不存在");

            return false;
        }
        $exportData = $this->dbconn->fetchAssoc("select rate,href from app_export where id=:id", array("id" => $row['export_id']));
        if (empty($exportData)) {
            $this->_error(402, "未找到任务");

            return false;
        }

        if ($exportData['rate'] == 100 && !empty($exportData['href'])) {
            $this->_error(403, "不允许重复执行");

            return false;
        }

        return true;
    }

    /**
     * 维护任务导出状态
     * @param string $exportId
     * @param string $type
     * @param string $rate
     * @param string $href
     * @param string $fileSize
     * @return bool
     */
    public function updateType($exportId, $type = "", $rate = "", $href = "", $fileSize = "")
    {
        $updateDate = array();
        if (!empty($type)) {
            $updateDate["type"] = $type;
        }
        if (!empty($rate)) {
            $updateDate["rate"] = $rate;
        }
        if (!empty($href)) {
            $updateDate["href"] = $href;
        }
        if (!empty($fileSize)) {
            $updateDate["file_size"] = $fileSize;
        }
        $this->dbconn->update("app_export", $updateDate, array('id' => $exportId));

        return true;
    }

    /**
     * 错误处理
     * @param $code
     * @param $message
     */
    private function _error($code, $message)
    {
        $this->result = array(
            "code" => $code,
            "message" => $message,
        );

        return;
    }

    /**
     * @param array $msgArray
     * @return mixed
     */
    public function proccessMsgArray($msgArray)
    {
        return $msgArray;
    }
}